#!/usr/bin/env python3

import sys
import os
import requests
from urllib.parse import urljoin

BASE_URL = "https://gitee.com/slcnx/ai_prompt/raw/master/rules/"

DOCUMENTS = [
    "README.md",
    "common-setup.md",
    "model.md",
    "serializer.md",
    "viewset.md",
    "urls.md",
    "frontend-setup.md",
    "frontend-api-client.md",
    "frontend-pages.md",
    "permissions-core.md"
]

def download_file(filename, target_dir):
    url = urljoin(BASE_URL, filename)
    print(url)
    filepath = os.path.join(target_dir, filename)

    try:
        print(f"正在下载: {filename}")
        response = requests.get(url, timeout=30)
        response.raise_for_status()

        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(response.text)

        print(f"✅ 成功下载: {filepath}")
        return True

    except requests.exceptions.RequestException as e:
        print(f"❌ 下载失败: {filename} - {str(e)}")
        return False
    except Exception as e:
        print(f"❌ 保存失败: {filename} - {str(e)}")
        return False



def main():
    if len(sys.argv) > 1:
        target_dir = sys.argv[1]
    else:
        target_dir = "."

    if not os.path.exists(target_dir):
        try:
            os.makedirs(target_dir)
            print(f"� 创建目录: {target_dir}")
        except Exception as e:
            print(f"❌ 无法创建目录 {target_dir}: {str(e)}")
            sys.exit(1)

    print("�🚀 全栈Web应用开发规范文档下载器")
    print("=" * 50)
    print(f"📂 目标目录: {os.path.abspath(target_dir)}")

    success_count = 0
    total_count = len(DOCUMENTS)

    print(f"\n📥 开始下载 {total_count} 个文档文件...")
    print("-" * 50)

    for filename in DOCUMENTS:
        if download_file(filename, target_dir):
            success_count += 1
        print()

    print("=" * 50)
    print(f"📊 下载完成: {success_count}/{total_count} 个文件成功")
    print(f"📂 文件保存在: {os.path.abspath(target_dir)}")

    if success_count == total_count:
        print("🎉 所有文档下载成功！")
    else:
        failed_count = total_count - success_count
        print(f"⚠️ 有 {failed_count} 个文件下载失败，请检查网络连接后重试")
        sys.exit(1)

if __name__ == "__main__":
    main()
